package org.br.erp.rfq.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.br.erp.base.entity.Scmpartner;
import org.br.erp.base.service.IScmpartnerService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.br.erp.rfq.entity.Scminquiryitem;
import org.br.erp.rfq.entity.Scminquiry;
import org.br.erp.rfq.vo.ScminquiryPage;
import org.br.erp.rfq.service.IScminquiryService;
import org.br.erp.rfq.service.IScminquiryitemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 询价单
 * @Author: jeecg-boot
 * @Date:   2023-01-13
 * @Version: V1.0
 */
@Api(tags="询价单")
@RestController
@RequestMapping("/rfq/scminquiry")
@Slf4j
public class ScminquiryController {
	@Autowired
	private IScminquiryService scminquiryService;
	@Autowired
	private IScminquiryitemService scminquiryitemService;

	@Autowired
	private IScmpartnerService scmpartnerService;
	
	/**
	 * 分页列表查询
	 *
	 * @param scminquiry
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "询价单-分页列表查询")
	@ApiOperation(value="询价单-分页列表查询", notes="询价单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<Scminquiry>> queryPageList(Scminquiry scminquiry,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Scminquiry> queryWrapper = QueryGenerator.initQueryWrapper(scminquiry, req.getParameterMap());
		Page<Scminquiry> page = new Page<Scminquiry>(pageNo, pageSize);
		IPage<Scminquiry> pageList = scminquiryService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param scminquiryPage
	 * @return
	 */
	@AutoLog(value = "询价单-添加")
	@ApiOperation(value="询价单-添加", notes="询价单-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ScminquiryPage scminquiryPage) {
		Scminquiry scminquiry = new Scminquiry();
		BeanUtils.copyProperties(scminquiryPage, scminquiry);
		scminquiryService.saveMain(scminquiry, scminquiryPage.getScminquiryitemList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param scminquiryPage
	 * @return
	 */
	@AutoLog(value = "询价单-编辑")
	@ApiOperation(value="询价单-编辑", notes="询价单-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ScminquiryPage scminquiryPage) {
		Scminquiry scminquiry = new Scminquiry();
		BeanUtils.copyProperties(scminquiryPage, scminquiry);
		Scminquiry scminquiryEntity = scminquiryService.getById(scminquiry.getId());
		if(scminquiryEntity==null) {
			return Result.error("未找到对应数据");
		}
		scminquiryService.updateMain(scminquiry, scminquiryPage.getScminquiryitemList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "询价单-通过id删除")
	@ApiOperation(value="询价单-通过id删除", notes="询价单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		scminquiryService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "询价单-批量删除")
	@ApiOperation(value="询价单-批量删除", notes="询价单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.scminquiryService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "询价单-通过id查询")
	@ApiOperation(value="询价单-通过id查询", notes="询价单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Scminquiry> queryById(@RequestParam(name="id",required=true) String id) {
		Scminquiry scminquiry = scminquiryService.getById(id);
		if(scminquiry==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(scminquiry);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "询价单分录通过主表ID查询")
	@ApiOperation(value="询价单分录主表ID查询", notes="询价单分录-通主表ID查询")
	@GetMapping(value = "/queryScminquiryitemByMainId")
	public Result<List<Scminquiryitem>> queryScminquiryitemListByMainId(@RequestParam(name="id",required=true) String id) {
		List<Scminquiryitem> scminquiryitemList = scminquiryitemService.selectByMainId(id);
		return Result.OK(scminquiryitemList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param scminquiry
    */
    @RequestMapping(value = "/exportXls")
    public List<ModelAndView> exportXls(HttpServletRequest request, Scminquiry scminquiry) {

		List<ModelAndView> res=new ArrayList<>();

      // Step.1 组装查询条件查询数据
      QueryWrapper<Scminquiry> queryWrapper = QueryGenerator.initQueryWrapper(scminquiry, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<Scminquiry> scminquiryList = scminquiryService.list(queryWrapper);

      // Step.3 组装pageList
      List<ScminquiryPage> pageList = new ArrayList<ScminquiryPage>();
      for (Scminquiry main : scminquiryList) {
          ScminquiryPage vo = new ScminquiryPage();
          BeanUtils.copyProperties(main, vo);
		  String vendorlinkid = vo.getVendorlinkid();
		  String[] split = vendorlinkid.split(",");

		  if(split!=null && split.length > 1 ){
			  for (String vendorid : split) {
				  //TODO 循环遍历获取供应商信息
				  List<Scminquiryitem> scminquiryitemList = scminquiryitemService.selectByMainId(main.getId());
				  Scmpartner scmpartner = scmpartnerService.getById(vendorid);
				  vo.setVendorlinkid(scmpartner.getPartnername());
				  vo.setScminquiryitemList(scminquiryitemList);
				  pageList.add(vo);
				  ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
				  mv.addObject(NormalExcelConstants.FILE_NAME, "询价单列表");
				  mv.addObject(NormalExcelConstants.CLASS, ScminquiryPage.class);
				  mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("询价单数据", "导出人:"+sysUser.getRealname(), "询价单"));
				  mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
				  mv.addObject(NormalExcelConstants.FILE_NAME,"询价单"+vo.getBillcode()+":"+scmpartner.getPartnername());
				  res.add(mv);
			  }
		  }else if(split!= null && split.length == 1)
		  {
			  List<Scminquiryitem> scminquiryitemList = scminquiryitemService.selectByMainId(main.getId());
			  vo.setScminquiryitemList(scminquiryitemList);
			  pageList.add(vo);

			  ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
			  mv.addObject(NormalExcelConstants.FILE_NAME, "询价单列表");
			  mv.addObject(NormalExcelConstants.CLASS, ScminquiryPage.class);
			  mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("询价单数据", "导出人:"+sysUser.getRealname(), "询价单"));
			  mv.addObject(NormalExcelConstants.DATA_LIST, pageList);

			  res.add(mv);
		  }
      }

      // Step.4 AutoPoi 导出Excel

      return res;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ScminquiryPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ScminquiryPage.class, params);
              for (ScminquiryPage page : list) {
                  Scminquiry po = new Scminquiry();
                  BeanUtils.copyProperties(page, po);
                  scminquiryService.saveMain(po, page.getScminquiryitemList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
